//引入的组件
import QuickScreen from "../../components/quick-screen.vue";//快速筛选
import ReplaceCourseware from "../../components/replace-courseware.vue";//替换课件弹窗组件
import OperationLog from "../../components/operation-log.vue";//操作日志弹窗组件
import TreeProject from "@rc/pages/components/async/tree-project.vue";//学员项目树
import EditDialog from "../../components/courseware-edit/layout-dialog.vue";
import EditBase from "../../components/courseware-edit/base.vue";
import EditProject from "../../components/courseware-edit/project.vue";
// 引入api
import coursewareApi from "@rc/apis/rc/courseware.mjs";
//Mixin
import Mixin from '../../mixin/index.mjs';
import filtrate from './filtrate.mjs';
import event from './event.mjs';

export default {
    name: 'rc-resource-audit',
    components:{
        QuickScreen,
        ReplaceCourseware,
        OperationLog,
        TreeProject,
        EditDialog,
        EditBase,
        EditProject
    },
    watch: {
        //当左侧项目树和上方快速搜索区域的初始化之后再去查询列表
        isInitQuickList(val) {
            val && this.onSubmit();
        },
    },
    mixins:[Mixin, event],
    computed:{
        selectTime(){
            const sec = this.selectItems.reduce(function(prev,cur){
                return prev + Number(cur.duration);
            }, 0);
            return sec;
        },
        // 当前编辑的课件基础详情
		editBaseInfo() {
			if (this.isEditBatchStatus) {
				// 批量编辑状态，传入空值
				return {
					sectionNumber: "",
					name: "",
					teacherId: "",
					professorName: "",
					sourceFileName: "",
					videoVid: ""
				};
			} else {
				// 单个编辑状态，传入详情
				return {
					sectionNumber: this.editInfo.sectionNumber,
					name: this.editInfo.name,
					teacherId: this.editInfo.teacherId,
					professorName: this.editInfo.professorName,
					sourceFileName: this.editInfo.sourceFileName,
					videoVid: this.editInfo.videoVid,
					livePlaybackState: this.editInfo.livePlaybackState,
				};
			}
		},
		// 当前编辑的课件项目详情
		editProjectInfo() {
			if (this.isEditBatchStatus) {
				// 批量编辑状态，传入空值
				return [];
			} else {
				// 单个编辑状态，传入详情
				return this.editInfo.rcDisposeResourceVideoProjectResponseVos.map((i) => ({
					...i,
					projectId: [i.projectId],
					subjectList: i.subjectList.map((i2) => i2.subjectId),
					subjectFullList: i.subjectList,
					seriesCourseList: i.seriesCourseList.map((i2) => i2.seriesCourseId)
				}));
			}
		},
    },
    data() {
        return {
            /** 资源列表分页器参数*/
            resourceQueryPagination: {
                pageIndex: 0,
                pageSize: 10,
                pageCount: 0
            },
            /**资源列表 */
            resourceList: [],
            /* 项目，子级项目，科目，章节 */
            chapterInfo: {},
            /* 列表查询加载中*/
            isShowLoading_table: false,
            isShowLoading_quick: false,
            isShowDeleteLoading: false,// 删除课件按钮
            isShowBatchQualityLoading: false,// 批量质检课件按钮
            isLoading: false, // 页面加载状态
			baseLoading: false, // 基础信息编辑的加载状态
			projectLoading: false, // 项目信息编辑的加载状态
			isShowEditDialog: false, // 是否显示编辑弹窗
			isEditBatchStatus: false, // 当前是否为批量编辑状态
            // [学院id,项目id]
            projectArr: [],
            projectId:"",
            // 章节
            checkedKey: '',
            // 快速筛选项
            quickList: [],
            isInitQuickList:false,//快速搜索区域是否初始化
            dialog: {
                isShowReplaceDialog: false,//替换文件弹窗
                isShowLogDialog: false, //日志弹窗
                isShowDeleteDialog: false, //删除资源弹窗
                isShowDeleteDialogResourceTip: false,
                isShowDeleteDialogCardTip: false,
            },
            resourceId:'',//当前替换的课件id
            selectItems: [],//选择的资源
            isCheckedAll: false, //是否全选了
            /* 搜索条件 */
            filtrate:filtrate(this),
            permissArr:[],//权限按钮
            pickerMinDate:'',//限制时间范围选择不能超过一年
            editInfo: {
				// 当前单个编辑的课件详情
				resourceId: "", //视频资源主键
				name: "", // 视频资源名称
				sectionNumber: "", // 节数
				sourceFileName: "", // 源文件名称
				videoVid: "", // 视频vid
				teacherId: "", // 授课老师标识
				professorName: "", // 授课老师名称
				livePlaybackState: "N", // 直播回放状态
				rcDisposeResourceVideoProjectResponseVos: [] // 项目列表
			},
            qualityStatusObj: null,
        };
    },
    created() {
        nlapp.PermissUtil.checkPagePermiss("rc/courseware/audit/qc-list");
        this.permissArr = this.getHasPermissArray();
        this.initQuickList();
        this.getQualityStatusList();
    },
    activated() {
        if(this.isInitQuickList) {
            this.permissArr = this.getHasPermissArray();
            if(this.$route.meta.fromPage === 'preview') {
                this.$refs.projectTreeRef.api_getProjectCount();
                this.resourceQueryPagination.pageIndex = this.$route.meta.pageIndex;
                this.onSearchResource();
            } else {
                this.onSubmit();
            }
        }
    },
    methods: {
        //获取权限
        getHasPermissArray(){
            let result = [];
            let PermissArray = [
                {
                    name:'预览',
                    permiss:'rc/courseware/audit/qc-preview',
                    eventName:'onPreview'
                },
                {
                    name:'质检通过',
                    permiss:'rc/courseware/audit/qc-check',
                    eventName:'qualityCourseWare'
                },
                {
                    name:'编辑',
                    permiss: '',
                    eventName:'onEdit'
                },
                {
                    name:'替换课件',
                    permiss:'rc/courseware/audit/qc-replace',
                    eventName:'onClickReplace'
                },
                {
                    name:'使用详情',
                    permiss:'rc/courseware/audit/qc-detail',
                    eventName:'onResourceDetail'
                },
                {
                    name:'删除',
                    permiss:'rc/courseware/audit/qc-delete',
                    eventName:'onDelete'
                },
                {
                    name:'操作日志',
                    permiss:'rc/courseware/audit/qc-log',
                    eventName:'onSearchLog'
                },
            ];
            PermissArray.forEach(permiss=>{
                if(PermissUtil.checkPermiss(permiss.permiss)){
                    result.push(permiss);
                }
            });
            return result;
        },
        // 点击单个修改
		onEdit(resourceId) {
			coursewareApi.queryFileInfo({
				data: { resourceId },
				success: (data) => {
					this.isEditBatchStatus = false;
					this.editInfo = data;
					this.isShowEditDialog = true;
				}
			});
		},
        /**
         * 审核弹窗-确定并继续审核
         */
        async onNextResourceAudit() {
            //继续审核下一个资源
            this.$refs.projectTreeRef.api_getProjectCount();
            this.resourceQueryPagination.pageIndex = 0;
            await this.onSearchResource();
            if(this.resourceList.length) {
                const resource = this.resourceList[0];
                this.resourceId = resource.resourceId;
            } else {
                this.closeAuditDialog();
                this.$message.success('待审核资源已全部审核完成');
            }
        },
        /**
         * 审核资源
         * @param {String} resourceId 资源id
         */
        onAudit(resourceId) {
            this.resourceId = resourceId;
            this.auditType="single";
            this.dialog.isShowAuditDialog = true;
        },
        onBatchAudit(){
            if (!this.selectIds.length) {
				this.$message.warning("请先选择课件!");
				return;
			}
            this.auditType="batch";
            this.resourceIds = this.selectIds;
            this.dialog.isShowAuditDialog = true;
        },
        closeAuditDialog() {
            this.resourceId = '';
            this.resourceIds = [];
            this.dialog.isShowAuditDialog = false;
        },
        initQuickList(){
             //前两年后两年
             let quickList = [];
             this.isShowLoading_quick = true;
             Http.callServices([{
                 url: 'rc/admin/common/teachstages', // RC30002 rc/admin/common/teachstages //教学阶段
             },{
                 url: 'rc/admin/common/resourcetypes', //RC30001 rc/admin/common/resourcetypes课件分类
             }
             ]).success((teachRange, livePlaybackState)=>{
                 quickList.splice(quickList.length-1,0,{
                     quickName:'资源类型',
                     key: 'livePlaybackState',
                     type: 'H',
                     enumData: livePlaybackState
                 },
                 {
                     quickName:'教学阶段',
                     key: 'teachRange',
                     type: 'H',
                     hasChildren:true,
                     enumData: teachRange
                 });

                 this.quickList = quickList;
             }).complete(()=>{
                 this.isShowLoading_quick = false;
             });
        },
        /**
         * 根据项目搜索科目和项目年份
         */
        getSubjectListByProjectId() {
            this.isInitQuickList = false;
            let project = this.$refs.projectTreeRef.api_getCurrentNode();
            this.projectId = project.projectId;
            this.$set(this.$refs.quickScreenRef.quickParams, 'subjectId','');
            this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId','');
            this.isShowLoading_quick = true;
            let quickList = this.quickList;
            Http.callServices([{
                url: 'bd/projectyear/list/simple',
                data:{
                    projectId: project.projectId,
                    pageIndex: 0, // 分页数据别删，否则数据可能异常
                    pageSize: 100
                }
            },{
                url: 'bd/subject/list/all',
                data:{
                    projectId: project.projectId,
                    subjectNature: 'S'
                }
            }]).success((yearList, subjectData)=>{
                subjectData = subjectData.data.map(item => ({
                    name: item.subjectName,
                    code: item.subjectId
                }));
                const subjectIndex = quickList.findIndex( item => item.key === 'subjectId');
                if(subjectIndex===-1) {
                    quickList.splice(quickList.length-1,0,{
                        quickName:'科目',
                        key: 'subjectId',
                        type: 'H',
                        enumData: subjectData
                    });
                } else {
                    quickList[subjectIndex].enumData = subjectData;
                }
                yearList = this.sortYear(yearList.data);
                yearList = yearList.map(item => ({
                    name: item.projectyearYear + '年',
                    code: item.projectyearId
                }));
                //const currentYear = new Date().getFullYear();
                const yearIndex = quickList.findIndex( item => item.key === 'applicableYearId');
                const isExists =  yearList.length > 0 ? yearList[0] : '';//yearList.find( item => item.name === currentYear + '年');
                const defaultYear = isExists ? isExists.code : '';
                this.$refs.quickScreenRef && this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId', defaultYear);
                if(yearIndex===-1) {
                    quickList.push({
                        quickName:'年份',
                        key: 'applicableYearId',
                        type: 'H',
                        enumData: yearList,
                        default:defaultYear
                    });
                } else {
                    quickList[yearIndex].enumData = yearList;
                    quickList[yearIndex].default =  defaultYear;
                }
                this.quickList = quickList;
            }).complete(() => {
                if(!this.isInitQuickList) {
                    this.isInitQuickList = true;
                }
                this.isShowLoading_quick = false;
            });
        },
        getQualityStatusList() {
            return coursewareApi.getQualityStatusList().then((res) => {
                const t = res.map((item) => {
                    return [item.code, item.name];
                });
                this.qualityStatusObj = Object.fromEntries(t);
                this.resourceList.forEach((item) => {
                    item.qualityStatusLabel = this.qualityStatusObj ? this.qualityStatusObj[item.qualityStatus] : '';
                });
            });
        },
    }
};
